package by.epam.trenings.vkphotorest.app;

import by.epam.trenings.vkphotorest.R;
import by.epam.trenings.vkphotorest.auth.VkOauth;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class VkLoginActivity extends Activity {

	private WebView mWebView;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (VkOauth.sign("") != null) {
			success.run();
		} else {
			setContentView(R.layout.activity_vk_login);
			mWebView = (WebView) findViewById(R.id.activity_vk_login_webView);

			WebSettings webSettings = mWebView.getSettings();

			webSettings.setJavaScriptEnabled(true);
			webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
			webSettings.setPluginsEnabled(true);
			mWebView.setWebViewClient(new VkWebViewClient());
			mWebView.loadUrl(VkOauth.AUTORIZATION_URL);
		}
	}

	private class VkWebViewClient extends WebViewClient {

		public VkWebViewClient() {
			super();

		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			showLoading();
			if (VkOauth.isRedirect(url)) {
				view.setVisibility(View.INVISIBLE);
			}
		}

		private void showLoading() {
			findViewById(R.id.activity_vk_login_progress).setVisibility(
					View.VISIBLE);
		}

		private void hideLoading() {
			findViewById(R.id.activity_vk_login_progress).setVisibility(
					View.GONE);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			if (!VkOauth.proceedRedirectURL(url, success)) {
				hideLoading();
			}
		}

	}

	private Runnable success = new Runnable() {

		@Override
		public void run() {
			setResult(RESULT_OK);

			Intent i = new Intent(VkLoginActivity.this, AlbumsActivity.class);
			startActivity(i);
			VkLoginActivity.this.finish();

		}

	};

}
